<template>
  <a-modal
    v-model:visible="visible"
    :width="600"
    wrap-class-name="user-role-modal"
    :maskClosable="false"
    title="角色分配"
  >
    <a-spin :spinning="loading">
      <a-row>
        <a-col v-for="(role, index) in roleList" :key="index" :span="6">
          <a-checkbox v-model:checked="role.checked">
            {{ role.roleName }}
          </a-checkbox>
        </a-col>
      </a-row>
    </a-spin>
    <template #footer>
      <a-button @click="cancel" :loading="loading">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
import systemApis from "@/apis/system";
export default defineComponent({
  name: "AssignRole",
  setup(props, { emit }) {
    const state = reactive({
      loading: false as boolean,
      visible: false as boolean,
      userId: undefined,
      roleIds: [] as Array<number>,
      roleList: [] as Array<any>,
    });
    const open = (userId: string | number) => {
      state.visible = true;
      state.userId = userId;
      getUserRole();
    };

    const cancel = () => {
      state.visible = false;
    };
    const getUserRole = async () => {
      try {
        state.loading = true;
        const userRoleRes: any = await systemApis.getRoleIdByUser(state.userId);
        if (userRoleRes.code === 0) state.roleIds = userRoleRes.data;
        console.log("用户绑定的角色id", state.roleIds);
        const roleListRes: any = await systemApis.selectRole(false);
        if (roleListRes.code === 0) state.roleList = roleListRes.data;
        console.log("角色列表", state.roleList);
        let idMap = {};
        state.roleIds.forEach((id) => {
          idMap[id] = true;
        });
        state.roleList.map((role) => {
          role.checked = idMap[role.id] ? true : false;
        });
        state.loading = false;
      } catch (err) {
        state.loading = false;
      }
    };
    const submit = async () => {
      console.log(state.roleList);
      // let roleIds =
      state.loading = true;
      let checkedRole = state.roleList.filter((item) => item.checked);
      let roleIds = checkedRole.map((item) => item.id);
      console.log(state.userId, roleIds);
      const res: any = await systemApis.updateUserRole({
        userId: state.userId,
        roleIds: roleIds,
      });
      state.loading = false;
      if (res.code === 0) {
        // cancel();
        state.visible = false;
        emit("submit");
      }
    };
    return {
      open,
      cancel,
      submit,
      ...toRefs(state),
    };
  },
});
</script>
<style lang="less" scoped>
</style>